<template>
  <div>
    <el-alert
      v-if="adminLevel < requiredLevel"
      title="(⊙o⊙)…您的权限不能访问此页面"
      type="warning"
      :closable="false"
    ></el-alert>
    <div v-else>
      <el-card
        shadow="hover"
        class="card"
      >
        <div slot="header">筛选条件</div>
        <el-form>
          <inputForm
            v-for="(item, id) in filterKeys"
            :key="id"
            :title="item.title"
            :index="id"
            @set="setFilter"
          ></inputForm>
        </el-form>
      </el-card>
      <el-card
        shadow="hover"
        class="card"
      >
        <div slot="header">输出项目</div>
        <el-collapse v-model="activeNames">
          <el-collapse-item
            title="基础信息"
            name="基础信息"
          >
            <!-- basic -->
            <el-checkbox-group v-model="basicExported">
              <el-checkbox label="name">姓名</el-checkbox>
              <el-checkbox label="clientName">OA名 </el-checkbox>
              <el-checkbox label="number">工作证号 </el-checkbox>
            </el-checkbox-group>
            <el-checkbox-group v-model="itemsExported">
              <el-checkbox label="身份证号">身份证号</el-checkbox>
              <el-checkbox label="出生日期">出生日期 </el-checkbox>
              <el-checkbox label="性别">性别 </el-checkbox>
            </el-checkbox-group>
            <p
              class="alert alert-warning"
              v-if="
              !basicExported.includes('name') &&
              !basicExported.includes('clientName')
            "
            >
              <strong>姓名</strong> 或 <strong>OA名</strong> 应至少选择一个
            </p>
          </el-collapse-item>
          <el-collapse-item
            title="筛选信息"
            name="筛选信息"
          >
            <!-- filtered -->
            <el-checkbox-group v-model="filterExported">
              <el-checkbox
                v-for="(item, id) in filterKeys"
                :key="id"
                :disabled="item.enable"
                :label="item.title"
              >
                {{ item.title }}
              </el-checkbox>
            </el-checkbox-group>
          </el-collapse-item>
          <el-collapse-item
            title="其他信息"
            name="其他信息"
          >
            <!-- extention -->
            <el-checkbox-group v-model="itemsExported">
              <el-checkbox
                v-for="(item, id) in exportList"
                :key="id"
                :label="item"
              >
                {{ item }}
              </el-checkbox>
            </el-checkbox-group>
          </el-collapse-item>
        </el-collapse>
      </el-card>
      <el-card
        shadow="hover"
        class="card"
      >
        <div slot="header">
          <span>筛选结果</span>
          <el-button
            v-if="matchedData!=null&&matchedData.length>0"
            type="text"
            style="float: right; padding: 3px"
            @click="cleanResult()"
          >清空结果</el-button>
          <el-button
            v-if="matchedData!=null&&matchedData.length>0"
            type="text"
            style="float: right; padding: 3px"
            @click="exportExcel()"
          >保存Excel文档</el-button>
        </div>
        <el-button
          v-if="matchedData==null||matchedData.length==0"
          type="primary"
          @click="getMatchedData()"
        >
          执行筛选
        </el-button>
        <el-table
          :data="tableDataNew.contents"
          style="width: 100%"
        >
          <el-table-column
            v-for="title in tableDataNew.titles"
            :key="title.bind"
            :prop="title.bind"
            :label="title.name"
          >
          </el-table-column>
        </el-table>
        <!-- <table
          class="table table-bordered table-hover"
          v-if="tableData"
        >
          <thead>
            <th
              v-for="(cell, id) in tableData.title"
              :key="id"
            >
              {{ cell }}
              </th>
          </thead>
          <tbody>
            <tr
              v-for="(row, id) in tableData.content"
              :key="id"
            >
              <td
                style="vnd.ms-excel.numberformat:@"
                v-for="(cell, id) in row"
                :key="id"
              >{{ cell }}</td>
            </tr>
          </tbody>
        </table> -->
      </el-card>
    </div>
  </div>
</template>

<script>
  import inputForm from "./inputForm.vue";
  export default {
    name: "filterView",
    components: {
      inputForm,
    },
    data() {
      return {
        requiredLevel: 2,
        activeNames: ["基础信息", "筛选信息"],
        ruleMain: "",
        ruleRoom: "",
        filterKeys: [
          { title: "进近管制注册有效期", enable: false, value: "", type: "<=" },
          // { title: "进近雷达注册有效期", enable: false, value: "", type: "<=" },
          { title: "体检合格证有效期", enable: false, value: "", type: "<=" },
          { title: "英语有效期", enable: false, value: "", type: "<=" },
          { title: "部门", enable: false, value: "", type: "==" },
          // { title: "职务", enable: false, value: "", type: "=" },
          // { title: "现聘任等级", enable: false, value: "", type: "=" },
          // { title: "教员级别", enable: false, value: "", type: "=" }
        ],
        itemsExported: [],
        filterExported: [],
        basicExported: ["name"],
        showExtention: false,
        matchedData: null,
        tableData: null,
        tableDataNew: [],
        resultString: "",
      };
    },
    computed: {
      adminLevel() {
        return this.$store.getters.adminLevel;
      },
      enabledFilters() {
        let f = new Array();
        for (let i = 0; i < this.filterKeys.length; i++) {
          if (this.filterKeys[i].enable) {
            f.push(this.filterKeys[i]);
          }
        }
        return f;
      },
      fullData() {
        return this.$store.state.fullData;
      },
      configList() {
        return this.$store.state.dataConfig;
      },
      filterList() {
        let l = new Array();
        for (let i = 0; i < this.filterKeys.length; i++) {
          l.push(this.filterKeys[i].title);
        }
        return l;
      },
      exportList() {
        let l = new Array();
        for (let i = 0; i < this.configList.length; i++) {
          if (
            this.configList[i].is_basic ||
            this.configList[i].is_calc ||
            this.filterList.includes(this.configList[i].title)
          ) {
            continue;
          }
          l.push(this.configList[i].title);
        }
        return l;
      },
    },
    methods: {
      cleanResult() {
        this.matchedData = null;
        this.tableData = null;
        this.tableDataNew = [];
        this.resultString = "";
      },
      cleanFilter() {},
      cleanExport() {},
      getDataID(val) {
        for (let i = 0; i < this.configList.length; i++) {
          if (this.configList[i].title == val) {
            return i;
          }
        }
      },
      getDataType(val) {
        for (let i = 0; i < this.configList.length; i++) {
          if (this.configList[i].title == val) {
            return this.configList[i].type;
          }
        }
      },
      convertValue(val, type) {
        if (val == "") {
          return -1;
        } else if (type == "DATE") {
          return new Date(val).getTime();
        } else if (type == "NUMBER") {
          return Number(val);
        } else {
          return val;
        }
      },
      setFilter(payload) {
        if (this.isDev) window.console.log(payload);
        this.filterKeys[payload.index].enable = payload.enable;
        this.filterKeys[payload.index].value = payload.value;
        if (this.isDev) window.console.log(this.filterKeys);
        if (payload.enable && !this.filterExported.includes(payload.title)) {
          this.filterExported.push(payload.title);
        }
      },
      getMatchedData() {
        this.matchedData = null;
        if (this.enabledFilters.length == 0) {
          return null;
        }
        let matchedData = new Array();
        for (let i = 0; i < this.fullData.length; i++) {
          let matched = 0;
          for (let j = 0; j < this.enabledFilters.length; j++) {
            for (let k = 0; k < this.fullData[i].extentionData.length; k++) {
              if (
                this.fullData[i].extentionData[k].itemTitle ==
                this.enabledFilters[j].title
              ) {
                let valueData = this.convertValue(
                  this.fullData[i].extentionData[k].itemValue,
                  this.getDataType(this.enabledFilters[j].title)
                );
                let valueFilter = this.convertValue(
                  this.enabledFilters[j].value,
                  this.getDataType(this.enabledFilters[j].title)
                );
                if (
                  this.enabledFilters[j].type == "<=" &&
                  valueData <= valueFilter
                ) {
                  matched++;
                  break;
                }
                if (
                  this.enabledFilters[j].type == "==" &&
                  valueData == valueFilter
                ) {
                  matched++;
                  break;
                }
              }
            }
          }
          if (matched == this.enabledFilters.length) {
            matchedData.push(this.fullData[i]);
          }
        }
        if (this.isDev) window.console.log('getContent', matchedData);
        this.matchedData = matchedData;
        this.$notify({ type: matchedData.length == 0 ? 'warning' : 'success', title: "筛选到" + matchedData.length + "条结果" });
        this.getContent();
      },
      getContent() {
        console.log('getContent');
        let tableData = { titles: new Array(), contents: new Array() };
        this.tableData = null;
        if (this.matchedData.length == 0) return null;
        let dataTitle = new Array();
        let dataContent = new Array();
        if (this.basicExported.includes("name")) {
          dataTitle.push("姓名");
          tableData.titles.push({ name: "姓名", bind: "name" });
        }
        if (this.basicExported.includes("clientName")) {
          dataTitle.push("OA名");
          tableData.titles.push({ name: "OA名", bind: "clientName" });
        }
        if (this.basicExported.includes("number")) {
          dataTitle.push("工作证号");
          tableData.titles.push({ name: "工作证号", bind: "number" });
        }
        // if (this.basicExported.includes("id_number")) dataTitle.push("身份证号");
        // if (this.basicExported.includes("birth_date")) dataTitle.push("出生日期");
        // if (this.basicExported.includes("sex")) dataTitle.push("性别");
        for (let i = 0; i < this.filterExported.length; i++) {
          dataTitle.push(this.filterExported[i]);
          tableData.titles.push({ name: this.filterExported[i], bind: this.filterExported[i] });
        }
        for (let i = 0; i < this.itemsExported.length; i++) {
          dataTitle.push(this.itemsExported[i]);
          tableData.titles.push({ name: this.itemsExported[i], bind: this.itemsExported[i] });

        }
        for (let i = 0; i < this.matchedData.length; i++) {
          // window.console.log(this.matchedData[i].basicData.name);
          let row = new Array();
          let line = {};
          if (this.basicExported.includes("name"))
            row.push(this.matchedData[i].basicData.name);
          line["name"] = this.matchedData[i].basicData.name;
          if (this.basicExported.includes("clientName"))
            row.push(this.matchedData[i].basicData.clientName);
          line["clientName"] = this.matchedData[i].basicData.clientName;
          if (this.basicExported.includes("number"))
            row.push(this.matchedData[i].basicData.number);
          line["number"] = this.matchedData[i].basicData.number;
          // if (this.basicExported.includes("id_number"))
          //   row.push(this.matchedData[i].basicData.id_number);
          // if (this.basicExported.includes("birth_date"))
          //   row.push(this.matchedData[i].basicData.birth_date);
          // if (this.basicExported.includes("sex"))
          //   row.push(this.matchedData[i].basicData.sex);
          for (let k = 0; k < this.filterExported.length; k++) {
            let val = "";
            for (let j = 0; j < this.matchedData[i].extentionData.length; j++) {
              if (
                this.filterExported[k] ==
                this.matchedData[i].extentionData[j].itemTitle
              ) {
                val = this.matchedData[i].extentionData[j].itemValue;
                break;
              }
            }
            row.push(val);
            line[this.filterExported[k]] = val;
          }
          for (let k = 0; k < this.itemsExported.length; k++) {
            let val = "";
            for (let j = 0; j < this.matchedData[i].extentionData.length; j++) {
              if (
                this.itemsExported[k] ==
                this.matchedData[i].extentionData[j].itemTitle
              ) {
                val = this.matchedData[i].extentionData[j].itemValue;
                break;
              }
            }
            row.push(val);
            line[this.itemsExported[k]] = val;
          }
          dataContent.push(row);
          tableData.contents.push(line);
        }
        this.tableData = { title: dataTitle, content: dataContent };
        this.tableDataNew = tableData;
        if (this.isDev) window.console.log(this.tableData);
        // this.getResultString();
        console.log('tableDataNew', this.tableDataNew);
      },
      copyResultString() {
        this.resultString = '';
        this.resultString = this.tableData.title.join("'\t") + "\n";
        for (let i = 0; i < this.tableData.content.length; i++) {
          this.resultString = this.resultString + this.tableData.content[i].join("'\t") + "\n";
        }
        this.$copyText(this.resultString).then(function (e) {
          this.$message.success('已复制，前往Excel中个粘贴')
          console.log(e)
        }, function (e) {
          this.$message.error('复制出错，请手动复制并下Excel中粘贴')
          console.log(e)
        });
      },
      exportExcel() {
        require.ensure([], () => {
          const { export_json_to_excel } = require("@/plugins/Export2Excel.js");
          const tHeader = [];
          // 上面设置Excel的表格第一行的标题
          const filterVal = [];
          // 上面的index、nickName、name是tableData里对象的属性
          for (let i = 0; i < this.tableDataNew.titles.length; i++) {
            tHeader.push(this.tableDataNew.titles[i].name);
            filterVal.push(this.tableDataNew.titles[i].bind);
          }
          const list = this.tableDataNew.contents;
          //把data里的tableData存到list
          const data = this.formatJson(filterVal, list);
          let fileName = "PIMS筛选结果" + new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString();
          export_json_to_excel(tHeader, data, fileName);
        });
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]));
      },
    },
    mounted() {
      if (this.adminLevel > 0) {
        if (!this.$store.state.staffList) this.$store.dispatch("getStaffList");
        if (!this.$store.state.fullData) this.$store.dispatch("getFullData");
      }
    },
  };
</script>

<style scoped>
  label {
    margin: 0.25em 0.1em 0.25em 0.5em;
  }

  .card {
    margin-bottom: 2em;
  }
</style>